//
//  StudentsEnjoyableAddViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/21.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "StudentsEnjoyableAddViewController.h"

#import "ReleaseView.h"

@interface StudentsEnjoyableAddViewController ()

@property (nonatomic, strong) ReleaseView * releaseView; // 发布尊享视图
@property (nonatomic, assign) CGFloat height;

@end

@implementation StudentsEnjoyableAddViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB_COLOR(0, 0, 0, 0.5);
    
    // 添加键盘监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 添加视图
    [self.view addSubview:self.releaseView];
    
    // 自动布局
    [_releaseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(11, 11));
        make.centerX.equalTo(self.view.mas_right).offset(SCREEN_WIDTH * - 0.12);
        make.centerY.equalTo(self.view.mas_top).offset(SCREEN_HEIGHT * 0.14);
    }];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 更新自动布局
    [_releaseView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.6, SCREEN_HEIGHT * 0.6));
        make.center.equalTo(self.view);
    }];
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    // 取到最上面文本输入框距离隐藏的高度
    _height = CGRectGetMinY(_releaseView.titleTextField.frame) + CGRectGetMinY(_releaseView.frame) - SCREEN_HEIGHT * 0.092;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 🌷🌷🌷event responds🌷🌷🌷
- (void)keyboardWillShow:(NSNotification *)notification {
    [self releaseViewMoved:notification.userInfo isShow:YES];
}
- (void)keyboardWillHide:(NSNotification *)notifacation {
    [self releaseViewMoved:notifacation.userInfo isShow:NO];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)releaseViewMoved:(NSDictionary *)userInfo isShow:(BOOL)isShow {
    // 键盘动画时长
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 动画
    [_releaseView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.6, SCREEN_HEIGHT * 0.6));
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).offset(isShow ? -_height : 0);
    }];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
- (void)addEnjoy {
    // 日期格式
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // POST 参数
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[dateFormatter dateFromString:_releaseView.startDateTextField.text] forKey:_type == 0 ? @"startTime" : @"startDate"];
    [parameters setObject:[dateFormatter dateFromString:_releaseView.stopDateTextField.text] forKey:_type == 0 ? @"endTime" : @"expDate"];
    [parameters setObject:_releaseView.titleTextField.text forKey:_type == 0 ? @"studentsEnjoy.title" : @"title"];
    [parameters setObject:[NSString getStringForEmojiString:_releaseView.contentTextView.text] forKey:_type == 0 ? @"studentsEnjoy.content" : @"content"];
    
    NSMutableDictionary * otherDateDic = [NSMutableDictionary dictionary];
    if (_type == 0) {
        NSData * data = UIImageJPEGRepresentation(_releaseView.imageView.image, 0.5);
        [otherDateDic setObject:data forKey:@"data"];
        [otherDateDic setObject:@"pic" forKey:@"key"];
        [otherDateDic setObject:[NSString stringWithFormat:@"%@.jpg", [NSString genaUUID]] forKey:@"fileName"];
        [otherDateDic setObject:@"image/jpeg" forKey:@"dataType"];
        
        [[NetTool sharedTool] requestMethod:POST loadingMsg:@"发布中..." url:BASEURLAPPEND(STUDENTSENJOYABLEADD_URL) otherData:otherDateDic parameters:parameters finish:^(id responseObject, NSError *error) {
            if (!error) {
                if ([responseObject[@"status"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"发布成功"];
                    
                    // 移除本视图与控制器
                    [self.view removeFromSuperview];
                    [self removeFromParentViewController];
                } else {
                    [MBProgressHUD showError:@"发布失败"];
                }
            } else {
                [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
            }
        }];
    } else {
        NSMutableArray * groupList = [NSMutableArray array];
        if (_releaseView.button1.selected) {
            [groupList addObject:_dataSource[0][@"id"]];
        }
        if (_releaseView.button2.selected) {
            [groupList addObject:_dataSource[1][@"id"]];
        }
        if (_releaseView.button3.selected) {
            [groupList addObject:_dataSource[2][@"id"]];
        }
        if (_releaseView.button4.selected) {
            [groupList addObject:_dataSource[3][@"id"]];
        }
        [parameters setObject:[groupList componentsJoinedByString:@";"] forKey:@"group"];
        
        [[NetTool sharedTool] requestMethod:POST loadingMsg:@"发布中..." url:BASEURLAPPEND(COMMUNITYINTERACTIONADD_URL) parameters:parameters finish:^(id responseObject, NSError *error) {
            if (!error) {
                if ([responseObject[@"status"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"发布成功"];
                    
                    // 移除本视图与控制器
                    [self.view removeFromSuperview];
                    [self removeFromParentViewController];
                } else {
                    [MBProgressHUD showError:@"发布失败"];
                }
            } else {
                [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
            }
        }];
    }
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (ReleaseView *)releaseView {
    if (!_releaseView) {
        _releaseView = [[ReleaseView alloc] initWithType:_type == 0 ? STUDENTSENJOYABLE : COMMUNITYINTERACTION SelectIndex:^(NSInteger selectBlock) {
            // 日期格式
            NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            if (selectBlock == 0) {
                if ([_releaseView.titleTextField.text isEqualToString:@""]) {
                    [MBProgressHUD showError:_type == 0 ? @"主题不能为空" : @"标题不能为空"];
                } else if ([_releaseView.startDateTextField.text isEqualToString:@""]) {
                    [MBProgressHUD showError:@"开始日期不能为空"];
                } else if ([_releaseView.stopDateTextField.text isEqualToString:@""]) {
                    [MBProgressHUD showError:@"截止日期不能为空"];
                } else if ([_releaseView.contentTextView.text isEqualToString:@""]) {
                    [MBProgressHUD showError:_type == 0 ? @"尊享内容不能为空" : @"内容不能为空"];
                } else if (_type == 0 && [_releaseView.imageView.image isEqual:[UIImage imageNamed:@"enjoy_添加图片.png"]]) {
                    [MBProgressHUD showError:@"尊享图片不能为空"];
                } else if ([_releaseView.startDateTextField.text compare:[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]]] == NSOrderedAscending) {
                    [MBProgressHUD showError:@"开始日期不能小于当前时间"];
                } else if ([_releaseView.stopDateTextField.text compare:_releaseView.startDateTextField.text] == NSOrderedAscending) {
                    [MBProgressHUD showError:@"结束日期不能小于开始日期"];
                } else {
                    [self addEnjoy];
                }
            } else {
                // 重新自动布局
                [_releaseView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.size.sizeOffset(CGSizeMake(11, 11));
                    make.centerX.equalTo(self.view.mas_right).offset(SCREEN_WIDTH * - 0.12);
                    make.centerY.equalTo(self.view.mas_top).offset(SCREEN_HEIGHT * 0.14);
                }];
                // 动画
                [UIView animateWithDuration:0.5 animations:^{
                    [self.view layoutIfNeeded];
                } completion:^(BOOL finished) {
                    // 动画完成后移除视图与控制器
                    [self willMoveToParentViewController:nil];
                    [self.view removeFromSuperview];
                    [self removeFromParentViewController];
                }];
            }
        }];
    }
    return _releaseView;
}

@end
